import React from 'react';
import { Card, Button, Modal, Form, Input, message } from 'antd';
import { ProTable, ProColumns } from '@ant-design/pro-table';
import { EditOutlined } from '@ant-design/icons';
import { getDriverList, bindDriverAccount } from '../../request/driver';
import { DriverDataRow, BindAccountPayload, BindAccountResponse } from '../../types/driver';

interface DriverData {
  key: string;
  name: string;
  phone: string;
  idNumber: string;
  vehicle: string;
  status: string;
  licenseExpiry: string;
  createTime: string;
  cardNum: string;
}

const DriverList: React.FC = () => {
  const [editModalVisible, setEditModalVisible] = React.useState(false);
  const [editingDriver, setEditingDriver] = React.useState<DriverData | null>(null);
  const [form] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();

  const columns: ProColumns<DriverData>[] = [
    {
      title: '司机姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    /*
    {
      title: '身份证号',
      dataIndex: 'idNumber',
      key: 'idNumber',
    },
    */
    {
      title: '车辆设备编号',
      dataIndex: 'vehicle',
      key: 'vehicle',
    },
    {
      title: '卡号',
      dataIndex: 'cardNum',
      key: 'cardNum',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      valueType: 'dateTime',
    },
    /*
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, record) => {
        let color = 'blue';
        let icon = <UserOutlined />;
        let text = '未知';
        
        switch (record.status) {
          case 'active':
            color = 'green';
            icon = <CheckCircleOutlined />;
            text = '在职';
            break;
          case 'inactive':
            color = 'red';
            icon = <StopOutlined />;
            text = '离职';
            break;
          case 'suspended':
            color = 'orange';
            icon = <ExclamationCircleOutlined />;
            text = '暂停';
            break;
        }
        return (
          <Tag color={color} icon={icon}>
            {text}
          </Tag>
        );
      },
    },
    */
    {
      title: '操作',
      key: 'action',
      valueType: 'option',
      render: (_, record) => [
        <Button 
          type="primary" 
          icon={<EditOutlined />} 
          key="edit"
          onClick={() => {
            handleEditDriver(record);
          }}
        >
          编辑
        </Button>,
      ],
    },
  ];

  const handleEditDriver = (driver: DriverData) => {
    setEditingDriver(driver);
    setEditModalVisible(true);
    // Use setTimeout to ensure the form is mounted before setting values
    setTimeout(() => {
      form.setFieldsValue({
        username: driver.name,
        phone: driver.phone,
        // cardNum is not included as it's not editable
      });
    }, 0);
  };

  const handleEditSubmit = async (values: BindAccountPayload) => {
    try {
      // Include the cardNum from the editing driver in the payload
      const payload: BindAccountPayload = {
        ...values,
        cardNum: editingDriver?.cardNum || ''
      };
      
      const response: BindAccountResponse = await bindDriverAccount(payload);
      if (response.code === '0000') {
        messageApi.success('司机账号绑定成功');
        setEditModalVisible(false);
        form.resetFields();
        // Refresh the table
        // You might want to trigger a refresh of the table data here
      } else {
        // 错误时保留模态框打开，显示错误信息，增加显示时长
        messageApi.error({
          content: response.message || '绑定失败，请检查输入信息后重试',
          duration: 5
        });
      }
    } catch (error: any) {
      console.error('Error binding driver account:', error);
      // Handle API error responses
      if (error.response && error.response.data) {
          // 显示API返回的错误信息，增加显示时长
          messageApi.error({
            content: error.response.data.message || '绑定司机账号失败，请检查输入信息后重试',
            duration: 5
          });
        } else if (error.message) {
          // 显示网络错误等信息，增加显示时长
          messageApi.error({
            content: error.message,
            duration: 5
          });
        } else {
          // 显示未知错误，增加显示时长
          messageApi.error({
            content: '绑定司机账号失败，请稍后重试',
            duration: 5
          });
        }
      // 错误时保留模态框打开，不重置表单
    }
  };

  return (
    <div>
      {contextHolder}
      <div style={{ padding: '24px 0' }}>  
        <Card 
          variant="outlined"
          styles={{ body: { padding: '24px' } }}
          style={{ 
            borderRadius: '8px',
            boxShadow: '0 2px 12px rgba(0, 0, 0, 0.05)'
          }}
        >
          <ProTable<DriverData>
            columns={columns}
            rowKey="key"
            pagination={{
              pageSize: 10,
            }}
            request={async (params) => {
              try {
                // Convert ProTable params to API params
                const apiParams = {
                  current: params.current,
                  size: params.pageSize,
                  ...params
                };
                
                const response = await getDriverList(apiParams);
                
                if (response.code === '0000') {
                  const formattedData = response.data.rows.map((item: DriverDataRow) => ({
                    key: item.id.toString(),
                    name: item.username || '',
                    phone: item.phone || '',
                    idNumber: '******************',
                    vehicle: item.dtuNumber || '未分配',
                    status: 'active',
                    licenseExpiry: '2025-12-31',
                    createTime: item.createTime,
                    cardNum: item.cardNum,
                  }));
                  
                  return {
                    data: formattedData,
                    success: true,
                    total: response.data.total,
                  };
                } else {
                  messageApi.error(response.message || '获取司机列表失败');
                  return {
                    data: [],
                    success: false,
                    total: 0,
                  };
                }
              } catch (error) {
                console.error('Error fetching driver list:', error);
                messageApi.error('获取司机列表失败');
                return {
                    data: [],
                    success: false,
                    total: 0,
                };
            }
            }}
            search={false}
            options={{
              setting: false,
              fullScreen: false,
              reload: false,
              density: false,
            }}
            bordered
          />
        </Card>
      </div>

      {/* Edit Driver Modal */}
      <Modal
        title="编辑司机账号"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        destroyOnHidden
      >
        <Form
          form={form}
          onFinish={handleEditSubmit}
          layout="vertical"
        >
          <Form.Item
            name="username"
            label="司机姓名"
            rules={[{ required: true, message: '请输入司机姓名' }]}
          >
            <Input placeholder="请输入司机姓名" />
          </Form.Item>
          
          <Form.Item
            name="phone"
            label="手机号"
            rules={[{ required: true, message: '请输入手机号' }]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DriverList;